const app = getApp()

const {
  liveClose,
  audienceLeaveLive,
  getMicCallList,
  getLiveRoomInfo,
  liveRejectCall
} = require('../../../api/live-api')
const {
  upLoadImg,
  getNewUserInfo,
} = require('../../../api/common.api')

var liveroom = require('../../../components/mlvb-live-room/mlvbliveroomcore.js');
let timer = null;
let getLiveInfoTimer = null;
let audioContext = null; // 音频播放对象
Page({
  component: null,
  data: {
    userName: '',
    roomID: '',
    roomName: '',
    avatar: '',
    pureAudio: false,
    role: 'audience',
    showLiveRoom: false,
    rooms: [],
    comment: [],
    linked: false,
    debug: false,
    frontCamera: true,
    // inputMsg: [],
    muted: false,
    toview: '',
    beauty: 5,
    shouldExit: false,
    phoneNum: '',
    headerHeight: app.globalData.headerHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    // cbPushURL:'',
    cover: "https://cebeiqiniu.nmhywl.cn/image/c85ca67f56a800ad72729a004a3d0592.png",
    userID: '',
    diamonds: 0, //   连麦收费
    micCallStatus: true, // 是否点击了麦序
    micCallList: [], // 麦序列表
    isHost:0, // 是否是主播
    msg: '', // 消息内容
    tapTime: '', // 禁用短时间内一直发送
    topNum: 0,
    audienceTopNum: 0,
    callTime: '', // 观众计时
    showCasterTime: false, // 显示主播计时

    livePeoplesNumber: 0, // 直播间观众人数
    currentUserName: '',
    currentUserId: ''
  },

  onLoad: function (options) {
    let _this = this;
    console.log("--> onLoad -crateLive: ", options)
    let role = options.type == 'create' ? 'anchor' : 'audience';
    // 设置直播背景图
    _this.setData({
      cover: options.cover,
      userID: options.userID,
      diamonds: options.diamonds,
      avatar: options.avatar,
      userName: options.userName,
      roomName: options.roomName,
    })
    if (role == 'audience') {
      _this.setData({
        roomID: options.roomID,
        role: role,
        showLiveRoom: true,
        pureAudio: JSON.parse(options.pureAudio),
      }, function () {
        _this.start();
      })
    } else {
      // @todo 直播参数通过上一个页面传入
      _this.setData({
        pureAudio: JSON.parse(options.pureAudio),
        role: role,
        showLiveRoom: true,
        roomID: options.roomID,
      }, function () {
        console.log('======> page data: ', _this.data)
        _this.start();
      })

      // 主播默认初始化铃声播放
      _this.initPlayer();
    }
  },
  // 初始化铃声
  initPlayer() {
    let _this = this
    //创建内部 audio 上下文 InnerAudioContext 对象。
    audioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false
    });
    audioContext.loop = true;
    audioContext.src = "https://cebeiqiniu.nmhywl.cn/attach/breeze.mp3"
  },
  /**
   * 底部充值弹出框事件
   */
  onShowRechargeModal() {
    let rechargeModal = this.selectComponent('#rechargeModal')
    rechargeModal.showModal()
  },

  onReady: function () {
    var _this = this;
    wx.setNavigationBarTitle({
      title: _this.data.roomName
    })
  },
  /**
   * 滚动到底部
   */
  scrollBottom() {
    let _this = this;
    setTimeout(() => {
      if (_this.data.role == 'audience') {
        wx.createSelectorQuery().select('#audience-chat-box').boundingClientRect(function (rect) {
          //滚动的高度=scroll-view内view的高度
          _this.setData({
            audienceTopNum: rect.height
          })
          // console.log(rect, '滚动到最底部……………………………………………………………………观众')
        }).exec()
      } else {
        wx.createSelectorQuery().select('#chat-box').boundingClientRect(function (rect) {
          //滚动的高度=scroll-view内view的高度
          _this.setData({
            topNum: rect.height
          })
          // console.log(rect.height, '滚动到最底部……………………………………………………………………主播')
        }).exec()
      }
    }, 1000);

  },

  getCurUserInfo() {
    let _this = this;
    getNewUserInfo().then(res => {
      _this.setData({
        currentUserName: res.nickname,
        currentUserId: res.userid
      })
      console.log(res, '最新的用户信息')
    })
  },
  /**
   * 设置发送消息
   */
  onMsgInput(e) {
    let msg = e.detail.value;
    this.setData({
      msg: msg
    })
  },
  onSendMsg() {
    let _this = this,
      nowTime = new Date();
    if (nowTime - _this.data.tapTime < 2000) {
      wx.showToast({
        title: '发送的频繁太快了',
        icon: 'none'
      })
      return
    } else {
      let sendMsg = {
        content: _this.data.msg,
        name: _this.data.currentUserName,
        type: 'txt',
      }
      _this.component && _this.component.sendTextMsg(JSON.stringify(sendMsg));
      _this.data.comment.push({
        content: sendMsg.content,
        name: '我',
        type: sendMsg.type,
      });
      _this.setData({
        comment: _this.data.comment,
        msg: ''
      });
      _this.scrollBottom();

    }
    _this.setData({
      'tapTime': nowTime
    });

  },
  // 计时器
  createTime() {
    let _this = this,
      m = 0,
      mm = 0;
    timer = setInterval(() => {
      mm += 1;
      if (mm >= 60) {
        m += 1;
        mm = 0
      }
      _this.setData({
        callTime: `${('0'+m).slice(-2)}:${('0'+mm).slice(-2)}`
      })
    }, 1000);
  },
  onRoomEvent: function (e) {
    var _this = this;
    var args = e.detail;
    console.log('onRoomEvent', args)
    switch (args.tag) {
      case 'roomClosed': {
        wx.showModal({
          content: `房间已解散`,
          showCancel: false,
          complete: () => {
            liveroom.logout();
            wx.switchTab({
              url: '../../index/index',
            })
          }
        });
        break;
      }
      case 'error': {
        wx.showToast({
          title: `${args.detail}[${args.code}]`,
          icon: 'none',
          duration: 1500
        })
        if (args.code == 5000) {
          this.data.shouldExit = true;
        } else {
          console.error("收到error:", args)
          if (args.code != -9004) {
            setTimeout(() => {
              wx.switchTab({
                url: '../../index/index',
              })
            }, 1500)
          } else {
            _this.setData({
              linked: false,
              phoneNum: ''
            })
          }
        }
        break;
      }
      case 'linkOn': { // 连麦连上
        // @todo 普通用户收到
        _this.setData({
          linked: true,
          phoneNum: ''
        })
        setTimeout(() => {
          _this.createTime(); // 开始时间
        }, 5000); // 延迟5秒计时
        break;
      }
      case 'linkOut': { //连麦断开
        _this.setData({
          linked: false,
          phoneNum: '',
          callTime: '',
          showCasterTime: false,
        })
        clearInterval(timer)

        // 暂停直播 3秒后恢复
        _this.component.pause()
        setTimeout(() => {
          _this.component.resume()
        }, 3500)

        break;
      }
      case 'casterLinkOut': { // 主播连麦断开事件
        // console.log('收到了主播断开连麦了…………………………………………主播连麦断开事件')
        clearInterval(timer)
        _this.setData({
          callTime: '',
          showCasterTime: false,
        })

        break;
      }
      case 'audienceInRoom': { // 观众进入直播间
        let sendMsg = {
          content: `***欢迎${_this.data.currentUserName}进入直播间***`,
          name: '主播',
          type: 'txt',
        }
        _this.component && _this.component.sendTextMsg(JSON.stringify(sendMsg));
        _this.data.comment.push({
          content: `***欢迎${_this.data.currentUserName}进入直播间***`,
          name: '主播',
          type: sendMsg.type,
        });
        _this.setData({
          comment: _this.data.comment,
        })
        break;
      }
      case 'recvTextMsg': {
        let msgObj = JSON.parse(e.detail.detail.msg._elements[0].content.text);
        // 如果图片对url进行解码        
        let con = msgObj.type == 'txt' ? msgObj.content : decodeURIComponent(msgObj.content);
        // console.log(con, '消息消息……………………………………………………')
        _this.data.comment.push({
          content: con,
          name: msgObj.name,
          type: msgObj.type,
        });

        _this.setData({
          comment: _this.data.comment,
        });
        _this.scrollBottom();
        break;
      }
      case 'requestJoinAnchor': { //收到连麦请求
        // @todo 主播账号收到消息
        audioContext.play();
        var jioner = args.detail;
        var showBeginTime = Math.round(Date.now());
        wx.showModal({
          content: `${jioner.userName} 请求连麦`,
          cancelText: '拒绝',
          confirmText: '接受',
          success: function (sm) {
            var timeLapse = Math.round(Date.now()) - showBeginTime;
            if (timeLapse < 10000) {
              if (sm.confirm) {
                audioContext.pause();
                console.log('用户点击同意')
                _this.component && _this.component.respondJoinAnchor(true, jioner, () => {
                  _this.createTime(); // 主播开始计时
                  _this.setData({
                    showCasterTime: true
                  })
                });

              } else if (sm.cancel) {
                console.log('用户点击拒绝')
                audioContext.pause();
                _this.component && _this.component.respondJoinAnchor(false, jioner);
              }
            } else {
              wx.showToast({
                title: '连麦超时',
              })

              liveRejectCall({
                live_id: _this.data.roomID,
                userid: jioner.userID,
              }).then(res => {
                audioContext.pause() // 暂停铃声
                clearInterval(timer)
                // 发送系统消息
                let sendMsg = {
                  content: `${jioner.userName} 请求连麦,主播长时间未接受已经超时取消`,
                  name: '系统提示',
                  type: 'txt',
                }
                _this.component && _this.component.sendTextMsg(JSON.stringify(sendMsg));
                _this.data.comment.push(sendMsg);

                _this.scrollBottom();

                _this.setData({
                  callTime: '',
                  showCasterTime: false,
                  comment: _this.data.comment,
                })
              })


            }
          }
        })
        break;
      }
      default: {
        console.log('onRoomEvent default: ', e)
        break;
      }
    }
  },
  /**
   * 传送图片
   */
  onSendImg() {
    let _this = this;
    upLoadImg((path) => {

      let sendMsg = {
        content: encodeURIComponent(path),
        name: _this.data.currentUserName,
        type: 'img',
      }
      _this.component && _this.component.sendTextMsg(JSON.stringify(sendMsg));
      _this.data.comment.push({
        content: path,
        name: '我',
        type: 'img',
      });
      _this.setData({
        comment: _this.data.comment,
        msg: '',
      });
      _this.scrollBottom();
    })
  },
  // 预览消息图片
  prevImg(e) {
    const {
      url
    } = e.currentTarget.dataset;
    wx.previewImage({
      current: url, // 当前显示图片的 http 链接
      urls: [url],
    })
  },
  start: function () {
    var _this = this;
    _this.component = _this.selectComponent("#id_liveroom")
    console.log('_this.component: ', _this.component)
    console.log('_this:', _this);
    _this.component.start();
    _this.getLiveRoomInfo();

  },
  /**
   * 获取直接间信息
   */
  getLiveRoomInfo() {
    let _this = this;

    getLiveInfoTimer = setInterval(() => {
      let params = {
        live_id: _this.data.roomID
      }
      getLiveRoomInfo(params).then(res => {
        _this.setData({
          livePeoplesNumber: res.online_member_num
        })
        console.log('直播间信息', res)
      })
    }, 10000);

  },
  onLinkClick: function () {
    let _this = this;
    console.log('连麦费用', _this.data.diamonds)
    if (_this.data.diamonds > 0) {
      wx.showModal({
        title: '提示',
        content: `该连麦费用为${_this.data.diamonds}元宝/分钟，确认连麦？`,
        success(res) {
          if (res.confirm) {
            _this.component && _this.component.requestJoinAnchor();
            _this.setData({
              phoneNum: 'phone-1'
            })
            _this.setInternal();

          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      _this.component && _this.component.requestJoinAnchor();
      _this.setData({
        phoneNum: 'phone-1'
      })
      _this.setInternal();
    }
    // _this.component && _this.component.requestJoinAnchor();
    // _this.setData({
    //   phoneNum: 'phone-1'
    // })
    // _this.setInternal();

  },
  setInternal: function () {
    var _this = this;
    setTimeout(() => {
      if (!_this.data.phoneNum) {
        return;
      }

      var curPhoneNum = '';
      switch (_this.data.phoneNum) {
        case 'phone-1':
          curPhoneNum = 'phone-2';
          break;
        case 'phone-2':
          curPhoneNum = 'phone-3';
          break;
        case 'phone-3':
          curPhoneNum = 'phone-1';
          break;
        default:
          break;
      }
      _this.setData({
        phoneNum: curPhoneNum
      })
      _this.setInternal();
    }, 500);
  },
  /**
   * 获取麦序列表
   */
  onGetMicCallList() {

    let _this = this;
    if (_this.data.micCallStatus) {
      getMicCallList({
        live_id: _this.data.roomID
      }).then(res => {
        console.log('麦序列表', res)
        _this.setData({
          micCallList: res.list,
          isHost: res.is_host
        })
        let micListModal = this.selectComponent('#getCallList')
        micListModal.showModal()
      })
    }

  },
  onLinkMicPeopleCLick(item) {
    let _this = this;
    // 再调用一下子组件踢人方法
    _this.component && _this.component.onCloseCallForUser(String(item.detail.user_id));
    clearInterval(timer)
    let micListModal = this.selectComponent('#getCallList')
    micListModal.hideModal()

    // console.log('// 再调用一下子组件踢人方法',item.detail.user_id,_this.component)
  },
  // goRoom: function (e) {
  //   var _this = this;
  //   var index = parseInt(e.currentTarget.dataset.index);
  //   var roomID = _this.data.rooms[index].roomID;
  //   _this.setData({
  //     roomID: roomID
  //   })
  // },
  /**
   * 静音事件
   */
  onMuteEvent() {
    this.setData({
      muted: !this.data.muted
    })
  },
  /**
   * 主播下播
   * @param {live_id == roomId}
   */
  onStopLive() {
    let _this = this;
    if (_this.data.showCasterTime) {
      wx.showToast({
        title: '您当前还在连麦中，请先断开连麦，再关闭直播间',
        icon: 'none',
        duration: 3000
      })
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定要下播吗？',
      success(res) {
        if (res.confirm) {
          liveClose({
            live_id: _this.data.roomID
          }).then((res) => {
            console.log(res, '主播结束下播了')
            clearInterval(timer)
            clearInterval(getLiveInfoTimer)
            _this.data.liveInfoTimer
            _this.setData({
              callTime: '',
              showCasterTime: false,
            })
            wx.switchTab({
              url: '../../index/index',
            })
          })
        }
      }
    })
  },
  /**
   * 观众离开直播间
   */
  onLaveLive() {
    let _this = this;
    if (_this.data.linked) {
      wx.showToast({
        title: '您当前还在连麦中，请先断开连麦，再退出直播间',
        icon: 'none',
        duration: 3000
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确定要离开直播间吗？',
      success(res) {
        if (res.confirm) {
          audienceLeaveLive({
            live_id: _this.data.roomID
          }).then(res => {
            liveroom.logout()
            clearInterval(timer)
            clearInterval(getLiveInfoTimer)
            _this.setData({
              callTime: '',
              showCasterTime: false
            })
            wx.switchTab({
              url: '../../index/index',
            })
          })
        }
      }
    })
  },
  onShareTimeline: function () { 
    let _this = this
    return {
      title: `我正在${_this.data.roomName}直播间看直播，你也一起来吧`,
      path: '/pages/index/index',
      imageUrl: 'https://cebeiqiniu.nmhywl.cn/image/5a29073faa378d01547e9ae21079f316.png'
    }
  } ,
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    var _this = this;
    if (this.data.shouldExit) {
      wx.showModal({
        title: '提示',
        content: "收到退房通知",
        showCancel: false,
        complete: function () {
          wx.navigateBack({
            delta: 1
          });
        }
      });
    }
    _this.component && _this.component.resume();
    wx.setKeepScreenOn({
      keepScreenOn: true,
      fail() { //如果失败 再进行调用
        wx.setKeepScreenOn({
          keepScreenOn: true
        });
      }
    });
    // 隐藏home按钮
    wx.hideHomeButton()
    _this.getCurUserInfo();
    _this.getWalletInfo();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var _this = this;
    _this.component && _this.component.pause();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var _this = this;
    clearInterval(timer)
    clearInterval(getLiveInfoTimer)
    _this.setData({
      callTime: '',
      showCasterTime: false
    })
    audioContext.pause();
    // liveroom.logout()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

    let _this = this;
    return {
      title: `我正在${_this.data.roomName}直播间看直播，你也一起来吧`,
      path: '/pages/index/index',
      imageUrl: 'https://cebeiqiniu.nmhywl.cn/image/5a29073faa378d01547e9ae21079f316.png'
    }
  },

  showLog: function () {
    var _this = this;
    _this.setData({
      debug: !_this.data.debug
    })
  },
  changeMute: function () {
    var _this = this;
    _this.setData({
      muted: !_this.data.muted
    })
  },
  // setBeauty: function () {
  // var _this = this;
  // _this.setData({
  //   beauty: _this.data.beauty == 5 ? 0 : 5
  // })
  // },
  // changeCamera: function () {
  //   var _this = this;
  //   _this.component && _this.component.switchCamera();
  //   _this.setData({
  //     frontCamera: !_this.data.frontCamera
  //   })
  // },
  // bindInputMsg: function (e) {
  //   this.data.inputMsg = e.detail.value;
  // },
  onBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },
})